/*****************************************************************************************
 **  Author:dgz master
 **  Contact：jiduxiong@dagongzao.com
 **
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import OrderInfo from '@/views/wmsproject/Components/OrderInfo.vue'
import printJS from 'print-js'
import { getWarehouseByRole } from '../customsJs/WarehouseRole'

import { ElMessage, ElMessageBox } from 'element-plus'
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter: OrderInfo,
    //新建、编辑弹出框扩展组件
    modelHeader: '',
    modelBody: '',
    modelRight: '',
    modelFooter: '',
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮
  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {
      //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      // this.buttons.push({  //也可以用push或者splice方法来修改buttons数组
      //   name: '打印', //按钮名称
      //   icon: 'el-icon-print', //按钮图标：https://element.eleme.cn/#/zh-CN/component/icon
      //   type: 'primary', //按钮样式:https://element-plus.gitee.io/zh-CN/component/button.html
      //   //color:"#eee",//自定义按钮颜色
      //   onClick: function () {
      //     this.$message.success('点击了按钮');
      //   }
      // });
      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;

      this.tableHeight = this.$HasChildrenPageHeight

      this.dragPosition = 'bottom'
    },

    async onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      //this.detailOptions.columns.forEach(column=>{ });
      //this.initColumnSelectTable()
      // this.columns.forEach(item=>{
      //   //冻结列
      //     if(item.field =="WarehouseId" || item.field=="OrderTypeId" || item.field =="OrderNo" ){
      //       item.fixed=true
      //     }
      //   })
      const WarehouseListByRole = await getWarehouseByRole()

      this.searchFormOptions.flat().forEach((i) => {
        if (i.field == 'WarehouseId') {
          i.data = WarehouseListByRole
        }
      })
      this.editFormOptions.flat().forEach((i) => {
        if (i.field == 'WarehouseId') {
          i.data = WarehouseListByRole
        }
      })

      let AddLine = this.detailOptions.buttons.find((i) => i.name == '添加行')
      AddLine.onClick = this.addDetailData

      this.createBtnByColumn()
      let tmp = this.editFormOptions.flat().find((i) => i.field == 'OrderNo')
      if (!!tmp) {
        tmp.extra = this.renderFormTip({
          title: '提示',
          content: '单号自动生成，无需填写',
        })
      }
    },
    printClick() {
      this.print()
    },
    print() {
      let that = this
      let rows = this.$refs.table.getSelected()
      if (!rows.length) return this.$message.error('请选择要打印的行')
      fetch(this.$api.WmsAmesJob + 'OrderPrint', {
        method: 'POST',
        body: JSON.stringify(rows.map((i) => i.OrderId)),
        headers: {
          'content-type': 'application/json',
          Authorization: this.$store.getters.getToken(),
        },
      })
        .then((r) => {
          return r.blob()
        })
        .then((b) => {
          let reader = new FileReader()
          reader.readAsText(b, 'UTF-8')
          reader.onload = function () {
            var content = this.result
            console.log(content, 'content')
            if (content.indexOf('"status":false,"code":null,"message":') >= 0) {
              var json = JSON.parse(content)
              that.$message.error(json.message)
              return
            }
            var pdfFile = window.URL.createObjectURL(b, { type: 'application/pdf' })
            printJS({
              printable: pdfFile,
              type: 'pdf',
              onPrintDialogClose: function () {
                that.search()
              },
            })
          }
        })
    },
    addDetailData() {
      let list = this.$refs.detail.rowData
      // 查找list中ItemOrder 最大值
      let maxItemOrder = list.length
        ? list.reduce((acc, cur) => {
            return acc.ItemOrder > cur.ItemOrder ? acc : cur
          }).ItemOrder
        : 0
      list.push({ ItemOrder: maxItemOrder + 10 })
    },
    createBtnByColumn() {
      let arr = [
        {
          type: 'warning',
          title: '撤销',
          disabled: (row, column, index) => {
            return row.OrderStatus == 0
          },
          onClick: (row, column, index) => {
            ElMessageBox.confirm(`确定要撤销${row.OrderNo}吗?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              center: true,
              type: 'warning',
            }).then((r) => {
              this.http.get(this.$api.order + 'CancelOrderById', { id: row.OrderId }).then((r) => {
                this.search()
                this.$message.success('撤销成功')
              })
            })
          },
        },
        {
          type: 'danger',
          title: '关单',
          disabled: (row, column, index) => {
            return row.OrderStatus == 2
          },
          onClick: (row, column, index) => {
            ElMessageBox.prompt('输入关单原因', 'Tip', {
              confirmButtonText: 'OK',
              cancelButtonText: 'Cancel',
            })
              .then(({ value }) => {
                this.http.get(this.$api.order + 'Completion', { id: row.OrderId, reason: value }).then((r) => {
                  this.$message.success('操作成功')
                  this.search()
                })
              })
              .catch(() => {})
          },
        },
      ]
      this.columns.push({
        title: '操作',
        field: '操作',
        width: 150,
        align: 'left',
        fixed: 'right',
        render: this.renderTableDoBtn(arr),
      })
    },
    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      return true
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true
    },
    updateBefore(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      return true
    },
    delBefore(formData, rows) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      let flag = rows.some((i) => i.OrderStatus != 0 && i.OrderStatus != 3)
      if (flag) {
        this.$message.error('只能删除未开始/已撤销的单据')
        return false
      }
      return true
    },
    addAfter(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      //添加后刷新字典
      this.initDicKeys()
      return true
    },
    updateAfter(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      //添加后刷新字典
      this.initDicKeys()
      return true
    },
    delAfter(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      //添加后刷新字典
      this.initDicKeys()
      return true
    },
    rowClick({ row, column, event }) {
      //存储当前选中的行数据
      this.$store.getters.data().OrderId = row.OrderId
      this.$store.getters.data().WarehouseIdByCahe = row.WarehouseId
      //查询界面table点击行事件
      this.$refs.table.$refs.table.clearSelection(row) //清除当前选中当前行;
      this.$refs.table.$refs.table.toggleRowSelection(row) //单击行时选中当前行;
      // 触发底部组件的自定义的点击事件
      this.$refs.gridFooter.topRowClick(row)
    },
    modelOpenAfter(row) {
      if (this.boxOptions.title == this.$ts('编辑')) {
        // 之所以这样，是因为this.currentAction 查看的时候也会变为update，回头再看
        if (row.OrderStatus != 0) {
          this.$message.error('只能编辑未开始的单据')
          this.boxInit = false
          this.boxModel = false
        }
      }

      // this.boxInit = false
      // this.boxModel = false
      //点击编辑、新建按钮弹出框后，可以在此处写逻辑，如，从后台获取数据
      //(1)判断是编辑还是新建操作： this.currentAction=='Add';
      //(2)给弹出框设置默认值
      //(3)this.editFormFields.字段='xxx';
      //如果需要给下拉框设置默认值，请遍历this.editFormOptions找到字段配置对应data属性的key值
      //看不懂就把输出看：console.log(this.editFormOptions)
    },
    destroyed() {
      this.$store.getters.data().OrderId = null
      this.$store.getters.data().WarehouseIdByCahe = null
    },
    initColumnSelectTable() {
      this.detail.columns.splice(1, 0, {
        field: 'MaterialName',
        title: '物料名称',
        type: 'excel',
        bind: { key: 'WMS_Material', data: [] },
        width: 110,
        edit: { type: 'selectTable' },
        align: 'left',
      })
      this.detail.columns.forEach((item) => {
        if (item.field == 'MaterialId') {
          item.hidden = true
        }
        if (item.field == 'MaterialName') {
          item.url = 'api/Bas_Material/getPageData'
          item.columns = [
            {
              field: 'MaterialId',
              title: '物品编号',
              type: 'string',
              width: 110,
              hidden: true,
            },
            {
              field: 'MaterialCode',
              title: '物品编码',
              type: 'string',
              width: 110,
            },
            {
              field: 'MaterialName',
              title: '物品名称',
              type: 'string',
              width: 110,
              search: true,
            },
            {
              field: 'MaterialType',
              title: '物品类型',
              type: 'string',
              width: 110,
            },
          ]

          //(输入框搜索)表格数据加载前处理
          item.loadBefore = (editRow, params, callback) => {
            //方式1、手动设置查询条件
            // params.wheres.push({
            //   name: 'MaterialName',
            //   value: editRow.MaterialName,
            //   displayType: 'like',
            // })
            let index = params.wheres.findIndex((item) => item.name == 'MaterialId')
            if (index > -1) {
              params.wheres.splice(index, 1)
            }
            callback(true)
          }
          item.onSelect = (editRow, rows) => {
            editRow.MaterialId = rows[0].MaterialId
            editRow.MaterialName = rows[0].MaterialName
          }
          //设置弹出框高度(默认200)
          item.height = 200
          //设置弹出框宽度(默认500)
          //item.width = 400;
          // item.textInline = false; //设置表格超出自动换行显示
          //设置表格是否单选
          item.single = true
          //设置是否显示分页
          item.paginationHide = false
        }
      })
    },
  },
}
export default extension
